// components/index-home/today-tasks/index.js
// 获取全局app实例
const app = getApp();
// 导入工具类
const storageManager = require('../../../manager/storageManager').getInstance();

Component({
  properties: {},
  data: {
    // 学习新单词任务
    newWordProgress: 0,
    completedNewWords: 0,
    totalNewWords: 0,
    // 复习单词任务
    reviewWordProgress: 0,
    completedReviewWords: 0,
    totalReviewWords: 0,
    // 奖励信息
    rewardMagicCoins: 0,
    // 当前词书信息
    currentBook: null,
    // 任务设置相关
    showTaskSettingsModal: false,
    maxNewWords: 10,  // 默认每日最多学习10个新单词
    maxReviewWords: 20, // 默认每日最多复习20个单词
    // 性能优化相关
    cachedTaskData: null,
    cacheExpireTime: null,
    isLoading: false
  },
  lifetimes: {
    attached() {
      // 注册到全局app实例，便于其他页面访问
      const app = getApp();
      if (!app.globalData) {
        app.globalData = {};
      }
      app.globalData.todayTasksComponent = this;
      
      // 使用全局学习数据管理器
      this.wordLearningDataManager = app.globalData.wordLearningDataManager;
      
      // 加载用户任务设置
      this.loadTaskSettings();
      
      // 设置加载状态
      this.setData({ isLoading: true });
      
      // 使用setTimeout实现延迟加载，避免阻塞页面渲染
      setTimeout(() => {
        this.loadTodayTasks();
        this.setData({ isLoading: false });
      }, 100);
    },
    
    detached() {
      // 组件卸载时，清除全局引用
      const app = getApp();
      if (app.globalData && app.globalData.todayTasksComponent === this) {
        app.globalData.todayTasksComponent = null;
      }
    }
  },
  methods: {
    // 加载用户任务设置
    loadTaskSettings() {
      try {
        const taskSettings = storageManager.getStorage(storageManager.STORAGE_KEYS.TASK_SETTINGS);
        if (taskSettings) {
          this.setData({
            maxNewWords: taskSettings.maxNewWords || 10,
            maxReviewWords: taskSettings.maxReviewWords || 20
          });
        }
      } catch (error) {
        console.error('加载任务设置失败:', error);
      }
    },
    
    // 加载今日任务数据
    loadTodayTasks() {
      try {
        // 检查是否有缓存且未过期
        const now = Date.now();
        const cacheDuration = 60 * 1000; // 缓存1分钟
        
        if (this.data.cachedTaskData !== null && 
            this.data.cacheExpireTime !== null && 
            now < this.data.cacheExpireTime) {
          // 使用缓存数据
          const cachedData = this.data.cachedTaskData;
          this.setData({
            newWordProgress: cachedData.newWordProgress,
            completedNewWords: cachedData.completedNewWords,
            totalNewWords: cachedData.totalNewWords,
            reviewWordProgress: cachedData.reviewWordProgress,
            completedReviewWords: cachedData.completedReviewWords,
            totalReviewWords: cachedData.totalReviewWords,
            rewardMagicCoins: cachedData.rewardMagicCoins,
            currentBook: cachedData.currentBook
          });
          return;
        }
        
        // 使用app中的全局实例
        const dm = app.getWordDataManager();
        const rs = app.getReviewScheduler();
        const magicCoinManager = app.getMagicCoinManager();
        
        // 保存到组件实例，方便其他方法使用
        this.magicCoinManager = magicCoinManager;
        
        // 获取当前词书（优先使用最近学习的词书）
        const currentBook = this._getCurrentWordBook();
        
        if (currentBook) {
          // 获取词书中的所有单词
          const allWords = dm.getWordsByBookId(currentBook.id);
          
          // 计算未学习的新单词数量
          const newWords = allWords.filter(word => !dm.getWordLearnedStatus(word.id));
          
          // 计算今日需要复习的单词数量
          const reviewWords = rs.getWordsForReview(currentBook.id);
          
          // 计算已学习的单词数量（今日新学的）
          const todayNewWords = this._getTodayNewWords(currentBook.id);
          
          // 计算今日已复习的单词数量
          const todayReviewWords = this._getTodayReviewWords(currentBook.id);
          
          // 设置任务目标（使用用户设置的最大数量）
          const newWordTarget = Math.min(newWords.length, this.data.maxNewWords);
          const reviewWordTarget = Math.min(reviewWords.length, this.data.maxReviewWords);
          
          // 计算奖励魔法币（完成任务获得）
          const rewardMagicCoins = Math.floor(newWordTarget * 5 + reviewWordTarget * 3);
          
          // 准备要更新的数据
          const taskData = {
            // 新单词任务数据
            newWordProgress: newWordTarget > 0 ? (todayNewWords / newWordTarget) * 100 : 0,
            completedNewWords: todayNewWords,
            totalNewWords: newWordTarget,
            // 复习单词任务数据
            reviewWordProgress: reviewWordTarget > 0 ? (todayReviewWords / reviewWordTarget) * 100 : 0,
            completedReviewWords: todayReviewWords,
            totalReviewWords: reviewWordTarget,
            // 奖励信息
            rewardMagicCoins: rewardMagicCoins,
            // 当前词书信息
            currentBook: currentBook,
            // 更新缓存
            cachedTaskData: {
              newWordProgress: newWordTarget > 0 ? (todayNewWords / newWordTarget) * 100 : 0,
              completedNewWords: todayNewWords,
              totalNewWords: newWordTarget,
              reviewWordProgress: reviewWordTarget > 0 ? (todayReviewWords / reviewWordTarget) * 100 : 0,
              completedReviewWords: todayReviewWords,
              totalReviewWords: reviewWordTarget,
              rewardMagicCoins: rewardMagicCoins,
              currentBook: currentBook
            },
            cacheExpireTime: now + cacheDuration
          };
          
          this.setData(taskData);
          
          // 保存任务数据到本地存储
          this._saveTaskData();
          
          // 使用setTimeout延迟执行非关键操作
          setTimeout(() => {
            this._checkAndRewardTaskCompletion();
          }, 300);
        }
      } catch (error) {
        console.error('加载今日任务数据失败:', error);
        // 失败时使用默认数据
        this._setDefaultTaskData();
      }
    },
    
    // 获取当前词书（激活状态的词书）
    _getCurrentWordBook() {
      // 使用app中的全局实例
      const dm = app.getWordDataManager();
      
      // 获取所有词书
      const allBooks = dm.getAllBooks();
      
      // 筛选出激活状态的词书
      const activeBook = allBooks.find(book => book.active === 1);
      if (activeBook) {
        return activeBook;
      }
      
      // 如果没有激活状态的词书，回退到使用最近学习的词书
      const wordDataManager = require('../../../manager/wordDataManager').getInstance();
const recentBookId = wordDataManager.getActiveBookId();
      if (recentBookId) {
        const recentBook = dm.getBookById(recentBookId);
        if (recentBook) {
          return recentBook;
        }
      }
      
      // 如果都没有，返回第一个可用的词书
      return allBooks.length > 0 ? allBooks[0] : null;
    },
    
    // 获取今日新学习的单词数量
    _getTodayNewWords(bookId) {
      try {
        // 使用app中的全局实例
        const dm = app.getWordDataManager();
        
        // 获取词书中的所有单词
        const words = dm.getWordsByBookId(bookId);
        
        // 获取今日日期的开始时间戳
        const todayStart = new Date();
        todayStart.setHours(0, 0, 0, 0);
        const todayStartTimestamp = todayStart.getTime();
        
        // 统计今日新学习的单词数量
      let count = 0;
      words.forEach(word => {
        // 使用WordLearningDataManager获取学习数据
        const learnCount = this.wordLearningDataManager.getWordLearnCount(word.id);
        const lastLearnTime = this.wordLearningDataManager.getWordLastLearnTime(word.id);
        
        if (lastLearnTime && learnCount === 1) {
          const learnTime = new Date(lastLearnTime).getTime();
          if (learnTime >= todayStartTimestamp) {
            count++;
          }
        }
      });
        
        return count;
      } catch (error) {
        console.error('获取今日新学习单词数量失败:', error);
        return 0;
      }
    },
    
    // 获取今日已复习的单词数量
    _getTodayReviewWords(bookId) {
      try {
        // 从本地存储获取今日已复习的单词数据
        const todayReviewData = storageManager.getStorage(storageManager.STORAGE_KEYS.TODAY_REVIEW_DATA) || {};
        return todayReviewData[bookId] || 0;
      } catch (error) {
        console.error('获取今日已复习单词数量失败:', error);
        return 0;
      }
    },
    
    // 保存任务数据到本地存储
    _saveTaskData() {
      const taskData = {
        newWordProgress: this.data.newWordProgress,
        completedNewWords: this.data.completedNewWords,
        totalNewWords: this.data.totalNewWords,
        reviewWordProgress: this.data.reviewWordProgress,
        completedReviewWords: this.data.completedReviewWords,
        totalReviewWords: this.data.totalReviewWords,
        rewardMagicCoins: this.data.rewardMagicCoins,
        lastUpdateTime: new Date().toISOString()
      };
      
      storageManager.setStorage(storageManager.STORAGE_KEYS.TODAY_TASK_DATA, taskData);
    },
    
    // 设置默认任务数据
    _setDefaultTaskData() {
      this.setData({
        newWordProgress: 0,
        completedNewWords: 0,
        totalNewWords: 5,
        reviewWordProgress: 0,
        completedReviewWords: 0,
        totalReviewWords: 10,
        rewardMagicCoins: 50,
        currentBook: null
      });
    },
    
    // 刷新任务数据
    refreshTasks() {
      this.loadTodayTasks();
    },
    
    // 检查并发放任务奖励
    _checkAndRewardTaskCompletion() {
      // 获取今天的日期作为任务ID
      const today = new Date();
      const todayDateString = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
      const taskId = `daily_task_${todayDateString}`;
      
      // 检查今日任务是否已完成且未领取奖励
      if (this.data.completedNewWords >= this.data.totalNewWords && 
          this.data.completedReviewWords >= this.data.totalReviewWords && 
          this.data.totalNewWords > 0 && this.data.totalReviewWords > 0 &&
          !this.magicCoinManager.hasTaskRewardClaimed(taskId)) {
        
        // 发放奖励
        const rewardAmount = this.data.rewardMagicCoins;
        if (this.magicCoinManager.addMagicCoins(rewardAmount)) {
          // 标记奖励已领取
          this.magicCoinManager.markTaskRewardAsClaimed(taskId);
          
          // 显示奖励领取成功提示
          wx.showToast({
            title: `恭喜获得${rewardAmount}魔法币！`,
            icon: 'success',
            duration: 2000
          });
        }
      }
    },
    
    // 显示任务设置弹窗
    showTaskSettings() {
      this.setData({
        showTaskSettingsModal: true
      });
    },
    
    // 隐藏任务设置弹窗
    hideTaskSettings() {
      this.setData({
        showTaskSettingsModal: false
      });
    },
    
    // 减少新单词上限
    decreaseNewWordLimit() {
      if (this.data.maxNewWords > 1) {
        this.setData({
          maxNewWords: this.data.maxNewWords - 1
        });
      }
    },
    
    // 增加新单词上限
    increaseNewWordLimit() {
      if (this.data.maxNewWords < 50) {
        this.setData({
          maxNewWords: this.data.maxNewWords + 1
        });
      }
    },
    
    // 减少复习单词上限
    decreaseReviewWordLimit() {
      if (this.data.maxReviewWords > 1) {
        this.setData({
          maxReviewWords: this.data.maxReviewWords - 1
        });
      }
    },
    
    // 增加复习单词上限
    increaseReviewWordLimit() {
      if (this.data.maxReviewWords < 100) {
        this.setData({
          maxReviewWords: this.data.maxReviewWords + 1
        });
      }
    },
    
    // 保存任务设置
  saveTaskSettings() {
    try {
      const taskSettings = {
        maxNewWords: this.data.maxNewWords,
        maxReviewWords: this.data.maxReviewWords,
        lastUpdateTime: new Date().toISOString()
      };
      
      // 保存到本地存储
      storageManager.setStorage(storageManager.STORAGE_KEYS.TASK_SETTINGS, taskSettings);
      
      // 重新加载任务数据
      this.loadTodayTasks();
      
      // 隐藏设置弹窗
      this.hideTaskSettings();
      
      // 显示保存成功提示
      wx.showToast({
        title: '设置已保存',
        icon: 'success'
      });
    } catch (error) {
      console.error('保存任务设置失败:', error);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  },
  
  // 主开始学习按钮 - 智能选择学习路径
  startLearning() {
    try {
      // 确保有当前词书
      if (!this.data.currentBook) {
        wx.showToast({
          title: '请先选择词书',
          icon: 'none'
        });
        return;
      }
      
      // 保存当前词书ID到本地存储
      // 不再存储最近使用的词书ID，而是通过激活状态来管理
      
      // 智能选择学习路径：优先复习（如果有复习任务且未完成）
      if (this.data.totalReviewWords > 0 && this.data.completedReviewWords < this.data.totalReviewWords) {
        // 有复习任务需要完成，跳转到复习页面
        wx.navigateTo({
          url: '/pages/vocabulary/review-magic/review-magic?bookId=' + this.data.currentBook.id
        });
      } else if (this.data.totalNewWords > 0 && this.data.completedNewWords < this.data.totalNewWords) {
        // 没有复习任务或复习任务已完成，跳转到学习新单词页面
        wx.navigateTo({
          url: '/pages/vocabulary/learning/learning?bookId=' + this.data.currentBook.id
        });
      } else {
        // 所有任务都已完成
        wx.showToast({
          title: '今日任务已全部完成',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('跳转到学习页面失败:', error);
      wx.showToast({
        title: '无法跳转到学习页面',
        icon: 'none'
      });
    }
  }
  }
})
